import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

/*
  Generated class for the RestProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export abstract class RestProvider {
	constructor(public http: HttpClient) {
		//console.log('Hello RestProvider Provider');
	}

	/**
	 * get 方法请求
	 * @param uri
	 */
	protected getUrlReturn(method: string, uri: string): Observable<string[]> {
		return this.http.request(method, uri).catch(this.handlerError);
	}

	/***
	 * 处理错误数据的走向
	 */
	private handlerError(error: HttpErrorResponse | any) {
		let errorMsg: string;
		if (error instanceof HttpErrorResponse) {
			const body = error.error || '';
			const err = body.error || JSON.stringify(body);
			errorMsg = `${error.status} - ${error.statusText || ''} ${err}`;
		} else {
			errorMsg = error.message ? error.message : error.toString();
		}
		console.error(errorMsg);
		return Observable.throw(errorMsg);
	}
}
